package com.arpa.ntocc.basic.api.controller;

import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.PartyGroupCacheDO;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.controller.BaseController;
import com.arpa.ntocc.common.domain.dto.DepartmentDTO;
import com.arpa.ntocc.common.domain.entity.Department;
import com.arpa.ntocc.common.domain.vo.DepartmentVO;
import com.arpa.ntocc.common.domain.vo.TreeData;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.ntocc.common.service.IDepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 部门信息 Controller
 * </p>
 *
 * @author LEO
 * @since 2019-12-17
 */
@Api(tags = "部门信息")
@RestController
@RequestMapping(value="/department", produces = "application/json;charset=UTF-8")
@Log4j2
public class DepartmentController extends BaseController {

   @Autowired
   private IDepartmentService  iDepartmentService;

    /**
     * 获取 部门信息 列表
     *
     * @param departmentDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 部门信息 列表", notes = "获取 部门信息 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DepartmentVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(DepartmentDTO departmentDTO, HttpServletRequest request) {
        try {
            //获取登录用户所属机构
            PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
            if (partyGroupCacheDO.getLevel() > 0) {
                departmentDTO.setPartyGroupCode(partyGroupCacheDO.getCode());
            }
            DepartmentVO departmentVOSum = iDepartmentService.queryListSum(departmentDTO);
            List<DepartmentVO> departmentVOList = iDepartmentService.queryList(departmentDTO);

            Page returnPage = new Page(departmentDTO.getPageNum(),departmentDTO.getPageSize());
            returnPage.setRecords(departmentVOList);
            returnPage.setTotal(departmentVOSum.getTotal());
            returnPage.setSumObject(departmentVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
    /**
     * 获取 部门信息级联 列表
     *
     * @param departmentDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 部门信息级联 列表", notes = "获取 部门信息级联 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DepartmentVO.class))
    @NeedLogin
    @GetMapping("/queryTreeData")
    public Result queryTreeData(DepartmentDTO departmentDTO, HttpServletRequest request) {
        try {
            //获取登录用户所属机构
            PartyGroupCacheDO partyGroupCacheDO =  UserUtil.getBranch();
            if (partyGroupCacheDO.getLevel() >= 0) {
                departmentDTO.setPartyGroupCode(partyGroupCacheDO.getCode());
            }
            List<TreeData> treeData = iDepartmentService.queryTreeData(departmentDTO);

            return Result.ok().data(treeData);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 部门信息
     *
     * @param entity Department
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 部门信息 ", notes = "添加 部门信息 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(Department.Save.class) Department entity, HttpServletRequest request) {
        try {
            entity.setPartyGroupCode(UserUtil.getBranchCode());
            iDepartmentService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取部门信息详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取部门信息详情", notes = "获取部门信息详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "部门信息code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Department.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result department(@PathVariable String code, HttpServletRequest request) {
        try {
            Department entity = iDepartmentService.getOne(new QueryWrapper<Department>().lambda().eq(Department::getCode,code));
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改部门信息
     *
     * @param entity 部门信息
     * @param request
     * @return
     */
    @ApiOperation(value = "修改部门信息", notes = "修改部门信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(Department.Update.class) Department entity, HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iDepartmentService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 部门信息
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 部门信息 ", notes = "删除 部门信息 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iDepartmentService.remove(new QueryWrapper<Department>().lambda().in(Department::getCode,codes));
            return Result.ok("操作成功！");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 获取 系统类型、计费类型级联数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 系统类型、计费类型级联数据", notes = "获取 系统类型、计费类型级联数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = TreeData.class))
    @NeedLogin
    @GetMapping("/cascadeData")
    public Result cascadeData(HttpServletRequest request) {
        try {
            List<TreeData> cascadeData = iDepartmentService.cascadeData();
            return Result.ok().data(cascadeData);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 系统类型、计费类型级联数据不包括集团
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 系统类型、计费类型级联数据不包括集团", notes = "获取 系统类型、计费类型级联数据不包括集团")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = TreeData.class))
    @NeedLogin
    @GetMapping("/cascadeDataNotLevel0")
    public Result cascadeDataNotLevel0(HttpServletRequest request) {
        try {
            List<TreeData> cascadeData = iDepartmentService.cascadeDataNotLevel0();
            return Result.ok().data(cascadeData);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取机构下的部门列表
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取机构下的部门列表", notes = "获取机构下的部门列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = TreeData.class))
    @NeedLogin
    @GetMapping("/getDepartmentList")
    public Result getDepartmentList(String groupCode,HttpServletRequest request) {
        try {
            List<DepartmentVO> departmentVOS = iDepartmentService.getDepartmentList(groupCode);
            return Result.ok().data(departmentVOS);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

 }
